package com.hippomeetsskunk.savanna.plot;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;

public class XYPlot extends ApplicationFrame {

	private static final long serialVersionUID = 1L;
	
	public XYPlot(String title, String legend, double[] x, double[] y) {
		super(title);

		XYSeries series = new XYSeries(legend);
		
		for(int i=0; i<x.length; ++i){
			series.add(x[i], y[i]);
		}
		XYSeriesCollection timeSeries = new XYSeriesCollection(series);
		ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
		final JFreeChart chart = ChartFactory.createXYLineChart(title, "time", "y", timeSeries, PlotOrientation.VERTICAL, true, false, false);

		// XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(0);
		// renderer.setSeriesShapesVisible(1, true);
		// renderer.setSeriesLinesVisible(1, false);
		        
        // add the chart to a panel...
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(750, 500));
        
        this.getContentPane().add(chartPanel);
	}

	public XYPlot(String title, String legend, List<Double> x, List<Double> y){
		this(title, legend, toDoubleArray(x), toDoubleArray(y));
	}
	
	public XYPlot(String title, List<XYSeries> series){
		super(title);
		XYSeriesCollection seriecCollection = new XYSeriesCollection();
		for(XYSeries s : series) seriecCollection.addSeries(s);
		ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
		final JFreeChart chart = ChartFactory.createXYLineChart(title, "time", "y", seriecCollection, PlotOrientation.VERTICAL, true, false, false);

        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(750, 500));
        this.getContentPane().add(chartPanel);
	}

    private static double[] toDoubleArray(Collection<Double> list){
    	double[] a = new double[list.size()];
    	Iterator<Double> it = list.iterator();
    	for(int i=0; it.hasNext(); ++i) a[i] = (it.next()).doubleValue();
    	return a;
    }
}
